package com.jt.www.admin.stats.controller;

import com.google.common.collect.Maps;
import com.jt.www.admin.stats.service.DataStatsService;
import com.jt.www.domain.dto.*;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.ResultDTO;
import com.jt.www.model.vo.stats.unifiedinsitemvo.ParamVO;
import com.jt.www.util.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author admin_ltf
 * @create 2019-05-13 09:28
 */
@Api(value = "教保网数据统计接口", tags = {"STATS-DATA-API"}, description = "教保网数据统计接口")
@RestController
@RequestMapping(value = "/stats/jbw")
public class DataStatsController {

    public static final Logger log = LoggerFactory.getLogger(DataStatsController.class);

    @Autowired
    private DataStatsService dataStatsService;

    /**
     * 导出汇总表
     *
     * @param inputDate
     * @param response
     * @param request
     */
    @ApiOperation(value = "导出汇总表", notes = "导出汇总表")
    @GetMapping(value = "/export/hzb", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportHzb(@ApiParam(value = "查询日期", required = true) @RequestParam("inputDate") String inputDate,
                          @ApiParam(value = "分支机构编码", required = true) @RequestParam("branchCode") String branchCode,
                          @ApiParam(value = "分支机构名称", required = true) @RequestParam("branchName") String branchName,
                          HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            String findCode = "exportHzb_" + System.currentTimeMillis();
            log.debug("{} 前端传递参数 inputDate:{}, branchCode:{}", findCode, inputDate, branchCode);
            ResponseEntity<GenericListResponse<HzbDto>> responseEntity = dataStatsService.hzbStatistic(inputDate, branchCode);

            List<HzbDto> list = new ArrayList<>();
            if (responseEntity.getBody() != null && "0000".equals(responseEntity.getBody().getCode())) {
                list = responseEntity.getBody().getList();
            }

            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("branchName", StringUtils.isEmpty(branchCode) ? "全国" : branchName);
            beanParams.put("year", inputDate.split("-")[0]);
            beanParams.put("month", inputDate.split("-")[1]);
            beanParams.put("items", list);

            //模板位置
            String path = "excel/templates/hzbstatistic.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);
            String fileName = "教育渠道汇总表.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出统保示范项目表
     *
     * @param inputDate
     * @param response
     * @param request
     */
    @ApiOperation(value = "导出统保示范项目表", notes = "导出统保示范项目表")
    @GetMapping(value = "/export/tbsfxm", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportTbsfxm(@ApiParam(value = "查询日期", required = true) @RequestParam("inputDate") String inputDate, HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            String findCode = "exportTbsfxm_" + System.currentTimeMillis();
            log.debug("{} 前端传递参数 {}", findCode, inputDate);
            ResponseEntity<GenericListResponse<TbsfxmDto>> responseEntity = dataStatsService.tbsfxmStatistic(inputDate);

            List<TbsfxmDto> list = new ArrayList<>();
            if (responseEntity.getBody() != null && "0000".equals(responseEntity.getBody().getCode())) {
                list = responseEntity.getBody().getList();
            }

            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("year", inputDate.split("-")[0]);
            beanParams.put("month", inputDate.split("-")[1]);
            beanParams.put("items", list);

            //模板位置
            String path = "excel/templates/tbsfxmstatistic.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);
            String fileName = "统保示范项目.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出延伸业务表
     *
     * @param inputDate
     * @param response
     * @param request
     */
    @ApiOperation(value = "导出延伸业务表", notes = "导出延伸业务表")
    @GetMapping(value = "/export/ysyw", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportYsyw(@ApiParam(value = "查询日期", required = true) @RequestParam("inputDate") String inputDate, HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            String findCode = "exportYsyw_" + System.currentTimeMillis();
            log.debug("{} 前端传递参数 {}", findCode, inputDate);
            ResponseEntity<GenericListResponse<YsywDto>> responseEntity = dataStatsService.ysywStatistic(inputDate);

            List<YsywDto> list = new ArrayList<>();
            if (responseEntity.getBody() != null && "0000".equals(responseEntity.getBody().getCode())) {
                list = responseEntity.getBody().getList();
            }

            List<String> projects = Lists.newArrayList();
            if (list != null && list.size() > 0) {
                for (YsywDetailDto detail : list.get(0).getYsywDetailDtos()) {
                    projects.add(detail.getBizType2Name());
                }
            }

            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("year", inputDate.split("-")[0]);
            beanParams.put("month", inputDate.split("-")[1]);
            beanParams.put("items", list);
            beanParams.put("projects", projects);

            //模板位置
            String path = "excel/templates/ysywstatistic.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);

            //开始进行合并单元格
            Sheet sheet = wb.getSheetAt(0);// 1 1
            //合并当年全年已确认保费
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 13 + projects.size() * 6));
            //合并项目
            for (int i = 0; i < projects.size(); i++) {
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 2 + i * 6, 7 + i * 6));
            }
            //本年当月情况
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 2 + projects.size() * 6, 6 + projects.size() * 6));

            String fileName = "延伸业务.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出区域统保业务表
     *
     * @param inputDate
     * @param response
     * @param request
     */
    @ApiOperation(value = "导出区域统保业务表", notes = "导出区域统保业务表")
    @GetMapping(value = "/export/qytb", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportQytb(@ApiParam(value = "查询日期", required = true) @RequestParam("inputDate") String inputDate, HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            String findCode = "exportQytb_" + System.currentTimeMillis();
            log.debug("{} 前端传递参数 {}", findCode, inputDate);
            ResponseEntity<GenericListResponse<QytbDto>> responseEntity = dataStatsService.qytbStatistic(inputDate);

            List<QytbDto> list = new ArrayList<>();
            if (responseEntity.getBody() != null && "0000".equals(responseEntity.getBody().getCode())) {
                list = responseEntity.getBody().getList();
            }

            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("year", inputDate.split("-")[0]);
            beanParams.put("month", inputDate.split("-")[1]);
            beanParams.put("items", list);

            //模板位置
            String path = "excel/templates/qytbstatistic.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);

            //开始进行合并单元格
            Sheet sheet = wb.getSheetAt(0);// 1 1
            int start = 3;
            int end = 0;
            for (int i = 0; i < list.size(); i++) {
                end = start + list.get(i).getQytbDetails().size() - 1;
                if (start != end) {
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 0, 0));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 1, 1));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 7, 7));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 8, 8));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 9, 9));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 10, 10));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 11, 11));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 12, 12));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 13, 13));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 14, 14));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 15, 15));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 16, 16));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 17, 17));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 18, 18));
                    sheet.addMergedRegion(new CellRangeAddress(start, end, 19, 19));
                }
                start = end + 1;
            }

            String fileName = "区域统保业务.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出我学保表
     *
     * @param inputDate
     * @param response
     * @param request
     */
    @ApiOperation(value = "导出我学保表", notes = "导出我学保表")
    @GetMapping(value = "/export/wxb", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportWxb(@ApiParam(value = "查询日期", required = true) @RequestParam("inputDate") String inputDate, HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            String findCode = "exportWxb_" + System.currentTimeMillis();
            log.debug("{} 前端传递参数 {}", findCode, inputDate);
            ResponseEntity<GenericListResponse<WxbDto>> responseEntity = dataStatsService.wxbStatistic(inputDate);

            List<WxbDto> list = new ArrayList<>();
            if (responseEntity.getBody() != null && "0000".equals(responseEntity.getBody().getCode())) {
                list = responseEntity.getBody().getList();
            }

            List<String> projects = Lists.newArrayList();
            if (list != null && list.size() > 0) {
                for (WxbDetailDto detail : list.get(0).getWxbDetailDtos()) {
                    projects.add(detail.getBizType2Name());
                }
            }

            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("year", inputDate.split("-")[0]);
            beanParams.put("lastYear", Integer.valueOf(inputDate.split("-")[0]) - 1);
            beanParams.put("month", inputDate.split("-")[1]);
            beanParams.put("items", list);
            beanParams.put("projects", projects);

            //模板位置
            String path = "excel/templates/wxbstatistic.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);

            //开始进行合并单元格
            Sheet sheet = wb.getSheetAt(0);// 1 1
            //合并当年全年已确认保费
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 10 + projects.size() * 7));
            //合并项目
            for (int i = 0; i < projects.size(); i++) {
                sheet.addMergedRegion(new CellRangeAddress(1, 2, 3 + i * 4, 6 + i * 4));
            }
            //本年当月情况
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 3 + projects.size() * 4, 5 + projects.size() * 7));
            for (int i = 0; i < projects.size(); i++) {
                sheet.addMergedRegion(new CellRangeAddress(2, 2, 3 + projects.size() * 4 + i * 3, 5 + projects.size() * 4 + i * 3));
            }

            String fileName = "我学保.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出学平险表
     *
     * @param inputDate
     * @param response
     * @param request
     */
    @ApiOperation(value = "导出学平险表", notes = "导出学平险表")
    @GetMapping(value = "/export/xpx", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void exportXpx(@ApiParam(value = "查询日期", required = true) @RequestParam("inputDate") String inputDate, HttpServletResponse response, HttpServletRequest request) {
        //解析结果
        try {
            String findCode = "exportXpx_" + System.currentTimeMillis();
            log.debug("{} 前端传递参数 {}", findCode, inputDate);
            ResponseEntity<GenericListResponse<XpxDto>> responseEntity = dataStatsService.xpxStatistic(inputDate);

            List<XpxDto> list = new ArrayList<>();
            if (responseEntity.getBody() != null && "0000".equals(responseEntity.getBody().getCode())) {
                list = responseEntity.getBody().getList();
            }

            Map<String, Object> beanParams = Maps.newHashMap();
            beanParams.put("year", inputDate.split("-")[0]);
            beanParams.put("month", inputDate.split("-")[1]);
            beanParams.put("items", list);

            //模板位置
            String path = "excel/templates/xpxstatistic.xls";
            Resource resource = new ClassPathResource(path);

            XLSTransformer transformer = new XLSTransformer();
            InputStream inputStream = resource.getInputStream();
            Workbook wb = transformer.transformXLS(inputStream, beanParams);
            String fileName = "学平险.xls";
            ExcelUtils.compParam(fileName, response, request);
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 汇总表
     *
     * @param orgCode
     * @return
     */
    @ApiOperation(value = "汇总表", notes = "根据orgCode汇总信息", httpMethod = "GET")
    @GetMapping(value = "/getInfoByOrgCode")
    @Deprecated
    public ResultDTO<Map<String, Object>> searchInfoByOrgCode(@ApiParam(value = "分支机构orgCode", required = false) @RequestParam(value = "orgCode", required = false) String orgCode) {


        ResultDTO resultMap = dataStatsService.searchInfoByOrgCode(orgCode);


        return resultMap;
    }

    /**
     * 统保示范项目表
     *
     * @return
     */
    @ApiOperation(value = "统保示范项目表", notes = "统保示范项目表", httpMethod = "POST")
    @PostMapping(value = "/getUnifiedInsItem")
    @Deprecated
//    public ResultDTO<List<UnifiedInsItemVO>> searchUnifiedInsItem() {
    public ResultDTO<Map<String, Object>> searchUnifiedInsItem(@RequestBody(required = false) ParamVO vo) {

        ResultDTO resultMap = dataStatsService.searchUnifiedInsItem(vo);


        return resultMap;
    }

    /**
     * 延伸业务
     *
     * @return
     */
    @ApiOperation(value = "延伸业务", notes = "延伸业务", httpMethod = "POST")
    @PostMapping(value = "/getExtendedBusiness")
    @Deprecated
//    public ResultDTO<List<ExtendBusinessVO>> searchExtendedBusiness() {
    public ResultDTO<Map<String, Object>> searchExtendedBusiness(@RequestBody(required = false) ParamVO vo) {

        ResultDTO resultMap = dataStatsService.searchExtendedBusiness(vo);

        return resultMap;
    }

    // Regional unification

    /**
     * 区域统保业务
     *
     * @return
     */
    @ApiOperation(value = "区域统保业务", notes = "区域统保业务", httpMethod = "POST")
    @PostMapping(value = "/getRegionalUnification")
    @Deprecated
//    public ResultDTO<List<RegionalUnificationVO>> searchRegionalUnification() {
    public ResultDTO<Map<String, Object>> searchRegionalUnification(@RequestBody(required = false) ParamVO vo) {


        ResultDTO resultMap = dataStatsService.searchRegionalUnification(vo);

        return resultMap;
    }

    /**
     * 我学保
     *
     * @return
     */
    @ApiOperation(value = "我学保", notes = "我学保", httpMethod = "POST")
    @PostMapping(value = "/getILearnInsured")
    @Deprecated
//    public ResultDTO<List<ILearnInsuredVO>> searchILearnInsured() {
    public ResultDTO<Map<String, Object>> searchILearnInsured(@RequestBody(required = false) ParamVO vo) {


        ResultDTO resultMap = dataStatsService.searchILearnInsured(vo);


        return resultMap;
    }


    /**
     * 学平险
     *
     * @return
     */
    @ApiOperation(value = "学平险", notes = "学平险", httpMethod = "POST")
    @PostMapping(value = "/getIStudentSafe")
    @Deprecated
//    public ResultDTO<List<StudentSafeVO>> searchStudentSafe() {
    public ResultDTO<Map<String, Object>> searchStudentSafe(@RequestBody(required = false) ParamVO vo) {


        ResultDTO resultMap = dataStatsService.searchStudentSafe(vo);


        return resultMap;
    }

    /**
     * 校车业务
     *
     * @return
     */
    @ApiOperation(value = "校车业务", notes = "校车业务", httpMethod = "POST")
    @PostMapping(value = "/getSchoolBus")
    @Deprecated
//    public ResultDTO<List<StudentBusVO>> searchSchoolBus() {
    public ResultDTO<Map<String, Object>> searchSchoolBus(@RequestBody(required = false) ParamVO vo) {


        ResultDTO resultMap = dataStatsService.searchSchoolBus(vo);


        return resultMap;
    }

    /**
     * 安全管理咨询业务  SafeManageConsultationVO
     *
     * @return
     */
    @ApiOperation(value = "安全管理咨询业务", notes = "安全管理咨询业务", httpMethod = "POST")
    @PostMapping(value = "/getSafeConsult")
    @Deprecated
//    public ResultDTO<List<SafeManageConsultationVO>> searchSafeConsult() {
    public ResultDTO<Map<String, Object>> searchSafeConsult(@RequestBody(required = false) ParamVO vo) {


        ResultDTO resultMap = dataStatsService.searchSafeConsult(vo);


        return resultMap;
    }
}
